﻿using Medallion.Threading;
using Microsoft.AspNetCore.Mvc;
using System.Net;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace HuaweiCloud.Dotnet.Samples.Cache4Redis.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IDistributedLockProvider _lockProvider;
        public ProductController(IDistributedLockProvider lockProvider)
        {
            _lockProvider = lockProvider;
        }
        // PUT api/<ProductController>/5
        [HttpPut("{id}/buy")]
        public async Task<IActionResult> Put(int id, [FromBody] BuyProductDto value)
        {
            var list = await ProductStore.GetAllAsync();
            var item = list.FirstOrDefault(x => x.Id == id);
            if (item == null)
                return NotFound();
            // 根据ID和前缀指定分布式锁标识
            var lockerName = $"product-{item.Id}";
            // 获取分布式锁，执行完毕后自动释放 或者在最大过期时间10秒后释放锁
            await using (await _lockProvider.AcquireLockAsync(lockerName, TimeSpan.FromSeconds(10)))
            {
                if (item.Count >= value.Count)
                {
                    var temp = item.Count;
                    await Task.Delay(100);
                    item.Count = temp - value.Count;
                }
            }
            return NoContent();
        }


        // GET: api/<ProductController>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Product>>> Get()
        {
            return await ProductStore.GetAllAsync();
        }

        // GET api/<ProductController>/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Product?>> Get(int id)
        {
            var list = await ProductStore.GetAllAsync();
            return Ok(list.FirstOrDefault(x => x.Id == id));
        }

        

        public class BuyProductDto
        {
            public int Count { get; set; }
        }
    }
}
